﻿using Library.Core.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using 软构大作业;

namespace Library.Core.Services
{
    public class LibraryService
    {
        private readonly List<Book> books;
        private readonly List<Reader> readers;
        private readonly List<BorrowRecord> records;

        public LibraryService()
        {
            books = new List<Book>();
            readers = new List<Reader>();
            records = new List<BorrowRecord>();
        }
        //借阅书籍
        public bool BorrowBook(int readerId, int bookId)
        {
            var reader = readers.FirstOrDefault(r => r.Id == readerId);
            var book = books.FirstOrDefault(b => b.Id == bookId);
            if (reader == null || book == null || !reader.CanBorrow || book.Stock <= 0)
                return false;

            book.Stock--;
            records.Add(new BorrowRecord
            {
                Id = records.Count + 1,
                ReaderId = readerId,
                BookId = bookId,
                BorrowDate = DateTime.Now,
                DueDate = DateTime.Now.AddDays(14),
                ReturnDate = null
            });
            return true;
        }
        //归还书籍
        public decimal ReturnBook(int readerId, int bookId, out bool wasOverdue)
        {
            var record = records.FirstOrDefault(r => r.ReaderId == readerId && r.BookId == bookId && r.ReturnDate == null);
            wasOverdue = false;
            if (record == null) return 0;

            record.ReturnDate = DateTime.Now;
            var book = books.First(b => b.Id == bookId);
            book.Stock++;

            decimal fine = 0;
            if (record.IsOverdue)
            {
                wasOverdue = true;
                var daysLate = (DateTime.Now - record.DueDate).Days;
                fine = daysLate * Constants.FinePerDay;

                var reader = readers.First(r => r.Id == readerId);
                reader.OverdueCount++;
                if (reader.OverdueCount > Constants.MaxOverdueCount)
                    reader.IsBlacklisted = true;
            }

            return fine;
        }
        //获取借阅期限
        public int GetOverdueDays()
        {
            int overdueDays = 0; // 默认值

            // SQL 查询语句
            string sql = "SELECT TOP 1 OverdueDays FROM library_db.admins";

            try
            {
                object result = Data.ExecuteScalar(sql); // 使用 Data 类的静态方法

                if (result != null && result != DBNull.Value)
                {
                    if (int.TryParse(result.ToString(), out int days))
                    {
                        overdueDays = days;
                    }
                    else
                    {
                        Console.WriteLine("无法将 OverdueDays 从数据库转换为整数。");
                    }
                }
                else
                {
                    Console.WriteLine("在 library_db.admins 表中没有找到 OverdueDays 的数据。");
                }
            }
            catch (Exception ex) // Data.ExecuteScalar 内部可能抛出异常
            {
                MessageBox.Show("获取 OverdueDays 时出错: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            return overdueDays;
        }
        //续借书籍
        public bool RenewBook(int readerId, int bookId)
        {
            var record = records.FirstOrDefault(r => r.ReaderId == readerId && r.BookId == bookId && r.ReturnDate == null);
            if (record == null || record.IsOverdue)
                return false;
            int days = GetOverdueDays();
            record.DueDate = record.DueDate.AddDays(days);
            return true;
        }
        //逾期检查，这个函数感觉有bug可以先不用或者后面改
        public void CheckOverdues()
        {
            foreach (var record in records)
            {
                if (record.IsOverdue)
                {
                    var reader = readers.FirstOrDefault(r => r.Id == record.ReaderId);
                    if (reader != null)
                    {
                        reader.OverdueCount++;
                        if (reader.OverdueCount > Constants.MaxOverdueCount)
                            reader.IsBlacklisted = true;
                    }
                }
            }
        }
        
        public List<Reader> GetBlacklistedReaders()
        {
            return readers.Where(r => r.IsBlacklisted).ToList();
        }
        //移出黑名单
        public bool RestoreReader(int readerId)
        {
            var reader = readers.FirstOrDefault(r => r.Id == readerId);
            if (reader == null) return false;

            reader.OverdueCount = 0;
            reader.IsBlacklisted = false;
            return true;
        }

        // 简单模拟数据添加，用于测试
        public void Seed()
        {
            books.Add(new Book { Id = 1, Title = "C#教程", Stock = 5 });
            readers.Add(new Reader { Id = 1, Name = "张三" });
        }
    }
}